package com.zd.springcloud.busy.service.impl;

import com.zd.springcloud.busy.service.BussinessService;
import com.zd.springcloud.config.ConsumerClient;
import com.zd.springcloud.config.GoodClient;
import com.zd.springcloud.config.OrderClient;
import com.zd.springcloud.domain.Good;
import com.zd.springcloud.domain.Order;
import com.zd.springcloud.enums.OrderStatus;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class BussinessServiceImpl implements BussinessService {


    @Autowired(required = false)
    GoodClient goodClient;

    @Autowired(required = false)
    OrderClient orderClient;


    @Autowired(required = false)
    ConsumerClient consumerClient;



    @Override
    @GlobalTransactional
    public String myMybussinee(long accountId,Long goodId,int num) {

        System.out.println(RootContext.inGlobalTransaction());
        System.out.println(RootContext.getXID());
        System.out.println(RootContext.getBranchType());

        //下订单的流程
        /**
         *
         *
         * 1、减库存
         * 2、扣钱
         * 3、添加订单
         *
         *
         */


        /**
         * 1.1 获取商品价格
         * 1.2 封装order实体
         * 1.3 调用订单的微服务
         */

        //1.1 获取商品价格
        Good good = goodClient.getGoodInfoById(goodId);




        /**
         * 2、减库存
         *
         */
        goodClient.reduceStock(num,goodId);


        /**
         *
         * 3、扣钱
         */
        consumerClient.reduceMoney(good.getGoodPrice()*num,accountId);

        //1.2 封装order实体
        Order order = new Order().setStatus(OrderStatus.CREATE.name()).
                setAccountId(accountId).setGoodId(goodId).
                setGoodNum(num);

        order.setOrderAmount(good.getGoodPrice()*num);
        //1.3 调用订单的微服务
        orderClient.addOrder(order);

        //int i = 10 / 0;
        return "success";
    }
}
